package org.nearby.note;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import org.nearby.note.utils.common;

/*
 * 局域网聊天工具服务端
 */
public class ChatServer extends JFrame implements ActionListener {
    private ServerSocket ss = null;
    private static ArrayList<Socket> socketList = new ArrayList<Socket>();

    private JPanel mainPanel = new JPanel();
    private JButton startBtn = new JButton("启动服务");
    private JButton stopBtn = new JButton("停止服务");

    private boolean is_running = false;

    public ChatServer() {
        initWin();
        initBind();

    }

    public void initWin() {
        this.setTitle("局域网聊天服务端");
        this.setSize(400, 400);
        this.setResizable(false);
        this.setVisible(true);

        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        mainPanel.setLayout(null);
        this.add(mainPanel);

        startBtn.setBounds(20, 20, 100, 30);

        startBtn.setFocusPainted(false);

        mainPanel.add(startBtn);

        stopBtn.setBounds(140, 20, 100, 30);

        stopBtn.setFocusPainted(false);

        mainPanel.add(stopBtn);

        stopBtn.setEnabled(false);
    }

    public void initBind() {
        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (ss != null && ss.isBound()) {
                    try {
                        ss.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        });
        startBtn.addActionListener(this);
        stopBtn.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("启动服务") && !is_running) {

            is_running = true;
            startBtn.setEnabled(false);
            stopBtn.setEnabled(true);
            
            new bindPort().start();

        } else if (e.getActionCommand().equals("停止服务") && is_running) {
            if (ss.isBound()) {
                try {
                    ss.close();
                    for (Socket s : ChatServer.socketList) {
                        if(s != null) s.close();
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                    JOptionPane.showMessageDialog(this, "无法停止服务");
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "出现错误");
        }

    }

    public static void main(String[] args) {
        new ChatServer();// 启动服务端
    }

    class bindPort extends Thread {
        public void run() {
            try {
                ss = new ServerSocket(30000, 10, InetAddress.getByName(common.getLocalIp()));

                while (true && ss.isBound()) {
                    Socket s = ss.accept();
                    socketList.add(s);
                    new Thread(new ServerThread(s)).start();
                }
            } catch (UnknownHostException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                //ex.printStackTrace();
            }

        }
    }

    class ServerThread implements Runnable {
        private Socket s = null;
        private BufferedReader br = null;

        public ServerThread(Socket s) {
            this.s = s;
            try {
                br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                String content = null;
                while ((content = readFromClient()) != null) {
                    for (Socket s : ChatServer.socketList) {
                        PrintStream ps;

                        ps = new PrintStream(s.getOutputStream());

                        ps.println(content);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String readFromClient() {
            try {
                return br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
                ChatServer.socketList.remove(s);
            }
            return null;
        }
    }
}
